package com.Xht.www.servlet;

//后端响应处理用户申请退款的请求

import com.Xht.www.dao.UserHistoryOrdersDAO;
import com.Xht.www.po.UserHistoryOrdersPO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/refundOrder")
public class RefundOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            int userId = Integer.parseInt(request.getParameter("userId"));

            UserHistoryOrdersDAO dao = new UserHistoryOrdersDAO();
            // 获取订单信息
            UserHistoryOrdersPO order = dao.getOrderById(orderId);

            if (order == null) {
                response.getWriter().write("订单不存在");
                return;
            }

            // 验证订单所属用户
            if (order.getUserId() != userId) {
                response.getWriter().write("无权操作此订单");
                return;
            }

            // 检查订单状态
            String currentStatus = order.getOrderStatus();
            if (!"正常".equals(currentStatus) && !"申请中".equals(currentStatus)) {
                response.getWriter().write("只有状态为正常或申请中的订单可以退款");
                return;
            }

            // 更新订单状态为"退款中"
            order.setOrderStatus("退款中");
            boolean success = dao.updateOrder(order);

            if (success) {
                response.getWriter().write("退款申请成功");
            } else {
                response.getWriter().write("退款申请失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("处理退款请求时出错");
        }
    }
}
